import 'dart:io';

import 'package:system_tray/system_tray.dart';

/// 系统工具类
class SystemUtil {

  /// 初始化系统托盘
  ///
  /// https://pub-web.flutter-io.cn/packages/system_tray
  ///
  /// [menus] 菜单项，可选项： 文本菜单 [MenuItemLabel]、 分割线 [MenuSeparator]、子菜单 [SubMenu]、勾选框菜单 [MenuItemCheckbox]
  static Future<void> initSystemTray(String iconPath, List<MenuItemBase> menus,
      {String? title, String? tooltip, bool isTemplate = false}) async {
    final AppWindow appWindow = AppWindow();

    final SystemTray systemTray = SystemTray();

    // We first init the systray menu
    await systemTray.initSystemTray(
      title: title,
      toolTip: tooltip,
      iconPath: iconPath,
      isTemplate: isTemplate,
    );

    // create context menu
    final Menu menu = Menu();
    await menu.buildFrom(menus);
    // set context menu
    await systemTray.setContextMenu(menu);

    // handle system tray event
    systemTray.registerSystemTrayEventHandler((eventName) {
      if (eventName == kSystemTrayEventClick) {
        Platform.isWindows ? appWindow.show() : systemTray.popUpContextMenu();
      } else if (eventName == kSystemTrayEventRightClick) {
        Platform.isWindows ? systemTray.popUpContextMenu() : appWindow.show();
      }
    });
  }
}
